<!--
 * @Description: 技师管理
 * @Author: xiao li
 * @Date: 2021-07-04 13:17:22
 * @LastEditTime: 2022-09-16 17:00:59
 * @LastEditors: xiao li
-->
<template>
  <div class="lb-examine">
    <top-nav />
    <div class="page-main">
      <lb-button
        size="medium"
        type="primary"
        icon="el-icon-plus"
        @click="$router.push(`/technician/edit`)"
        >{{ $t('menu.TechnicianAdd') }}</lb-button
      >
      <div class="space-lg"></div>
      <el-row class="page-top-operate">
        <el-button
          @click="toChange(0)"
          :type="searchForm.status === 0 ? 'primary' : ''"
          plain
          size="medium"
          >全部（{{ count.all || 0 }}）</el-button
        >
        <el-button
          @click="toChange(4)"
          :type="searchForm.status === 3 ? 'primary' : ''"
          plain
          size="medium"
          >未授权（{{ count.nopass || 0 }}）</el-button
        >
        <el-button
          @click="toChange(1)"
          :type="searchForm.status === 1 ? 'primary' : ''"
          plain
          size="medium"
          >申请中（{{ count.ing || 0 }}）</el-button
        >
        <el-button
          @click="toChange(2)"
          :type="searchForm.status === 2 ? 'primary' : ''"
          plain
          size="medium"
          >已授权（{{ count.pass || 0 }}）</el-button
        >
        <el-button
          @click="toChange(-1)"
          :type="searchForm.status === -1 ? 'primary' : ''"
          plain
          size="medium"
          >重新审核（{{ count.update || 0 }}）</el-button
        >
      </el-row>
      <el-row class="page-search-form">
        <el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm"
          ref="searchForm"
        >
          <el-form-item label="输入查询" prop="name">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入技师姓名/手机号"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-form-item label="申请时间" prop="start_time">
              <el-date-picker
                @change="getTableDataList(1)"
                v-model="range"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                value-format="timestamp"
              ></el-date-picker>
            </el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="work_img" label="技师头像">
          <template slot-scope="scope">
            <lb-image :src="scope.row.work_img" />
          </template>
        </el-table-column>
        <el-table-column prop="coach_name" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="create_time" label="申请时间" min-width="120">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="admin_add" label="申请人">
          <template slot-scope="scope">
            <el-tag :type="addText[scope.row.admin_add].type">{{
              addText[scope.row.admin_add].text
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="认证状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.user_id">已认证</el-tag>
            <el-tag type="danger" v-if="!scope.row.user_id">暂未认证</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="statusText[scope.row.status].type">
              {{ statusText[scope.row.status].text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="admin_name"
          label="所属代理商"
          min-width="120"
        ></el-table-column>

        <el-table-column label="操作" min-width="220">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="toShowApply(scope.row.id)"
                v-if="
                  scope.row.status !== 1 &&
                  scope.row.status !== 3 &&
                  !scope.row.admin_add
                "
                >{{ $t('action.view') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="toShowApply(scope.row.id, 2)"
                v-if="scope.row.is_update === 1"
                >重新审核</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="$router.push(`/technician/edit?id=${scope.row.id}`)"
                v-if="scope.row.admin_add === 1"
                >{{ $t('action.edit') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="confirmDel(scope.row.id, -1)"
                v-if="userInfo.is_admin == 1 && scope.row.status !== 1"
                >{{ $t('action.delete') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="success"
                @click="toShowApply(scope.row.id)"
                v-if="
                  userInfo.is_admin == 1 &&
                  (scope.row.status === 1 || scope.row.status == 3)
                "
                >{{
                  scope.row.status === 1 ? '授权为技师' : '重新授权为技师'
                }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="success"
                @click="confirmDel(scope.row.id, 3)"
                v-if="userInfo.is_admin == 1 && scope.row.status === 2"
                >取消授权</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="warning"
                @click="confirmedit(scope.row)"
                v-if="userInfo.is_admin == 1"
                >修改代理商</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="false"
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      </lb-page>
      <el-dialog
        title="申请详情"
        :visible.sync="showApply"
        width="800px"
        center
      >
        <div style="height: 60vh; overflow: auto" v-if="showApply">
          <el-form
            @submit.native.prevent
            :model="applyForm"
            label-width="130px"
            size="mini"
          >
            <div class="flex-warp">
              <el-form-item label="用户ID：" style="width: 50%">
                <div>{{ applyForm.user_id }}</div>
              </el-form-item>
              <el-form-item label="昵称：" style="width: 50%">
                <div>{{ applyForm.nickName }}</div>
              </el-form-item>
            </div>
            <el-form-item label="姓名：">
              <div>{{ applyForm.coach_name }}</div>
            </el-form-item>
            <el-form-item label="性别：">
              <div>{{ applyForm.sex === 0 ? '男' : '女' }}</div>
            </el-form-item>
            <el-form-item label="手机号：">
              <div>{{ applyForm.mobile }}</div>
            </el-form-item>
            <el-form-item label="从业年份：">
              <div>{{ applyForm.work_time }}年</div>
            </el-form-item>
            <el-form-item label="意向工作城市：">
              <div>{{ applyForm.city }}</div>
            </el-form-item>
            <el-form-item label="所在地址：">
              <div>{{ applyForm.address }}</div>
            </el-form-item>
            <el-form-item label="技师简介：">
              <div>{{ applyForm.text }}</div>
            </el-form-item>
            <el-form-item label="身份证号：">
              <div>{{ applyForm.id_code }}</div>
            </el-form-item>
            <el-form-item label="身份证正反面：">
              <div class="flex-warp">
                <lb-cover
                  :fileList="applyForm.id_card"
                  :isToDel="false"
                  size="small"
                  type="more"
                  :fileSize="applyForm.id_card.length"
                ></lb-cover>
              </div>
            </el-form-item>
            <el-form-item label="资格证书：">
              <div class="flex-warp">
                <lb-cover
                  :fileList="applyForm.license"
                  :isToDel="false"
                  size="small"
                  type="more"
                  :fileSize="applyForm.license.length"
                ></lb-cover>
              </div>
            </el-form-item>
            <el-form-item label="工作形象照：">
              <div class="flex-warp">
                <lb-cover
                  :fileList="[{ url: applyForm.work_img }]"
                  :isToDel="false"
                  size="small"
                  type="more"
                  :fileSize="1"
                ></lb-cover>
              </div>
            </el-form-item>
            <el-form-item label="个人生活照：">
              <div class="flex-warp">
                <lb-cover
                  :fileList="applyForm.self_img"
                  :isToDel="false"
                  size="small"
                  type="more"
                  :fileSize="applyForm.self_img.length"
                ></lb-cover>
              </div>
            </el-form-item>
            <el-form-item label="个人视频介绍：" v-if="applyForm.video">
              <video
                controls
                width="500"
                height="300"
                :src="applyForm.video"
              ></video>
            </el-form-item>
            <div class="space-lg"></div>
            <div class="space-lg b-1px-t"></div>
            <div class="space-lg"></div>
            <block v-if="applyForm.status !== 1">
              <div class="flex-warp">
                <el-form-item
                  label="审核结果："
                  prop="status"
                  style="width: 50%"
                >
                  <el-tag :type="statusText[applyForm.status].type">{{
                    statusText[applyForm.status].text
                  }}</el-tag>
                </el-form-item>
                <el-form-item
                  label="审核时间："
                  prop=""
                  style="width: 50%"
                  v-show="applyForm.status != 1 && applyForm.sh_time"
                >
                  <div class="c-warning">
                    {{ applyForm.sh_time | handleTime() }}
                  </div>
                </el-form-item>
              </div>
              <el-form-item
                label="审核意见："
                prop="sh_text"
                v-if="applyForm.sh_text"
              >
                <div>{{ applyForm.sh_text }}</div>
              </el-form-item>
            </block>
          </el-form>
          <el-form
            @submit.native.prevent
            :model="subForm"
            ref="subForm"
            :rules="subFormRules"
            label-width="130px"
            size="mini"
            v-if="applyForm.status === 1 || applyForm.status == 3"
          >
            <el-form-item label="审核结果：" prop="status" style="width: 50%">
              <el-radio-group v-model="subForm.status">
                <el-radio :label="2">通过</el-radio>
                <el-radio :label="4" v-if="applyForm.status === 1"
                  >驳回</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审核意见：">
              <el-input
                type="textarea"
                :rows="10"
                v-model="subForm.sh_text"
                maxlength="300"
                show-word-limit
                resize="none"
                placeholder="请输入审核意见"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showApply = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button
            type="primary"
            @click="submitForm"
            v-if="applyForm.status === 1 || applyForm.status === 3"
            >{{ $t('action.comfirm') }}</el-button
          >
        </span>
      </el-dialog>

      <el-dialog
        title="选择代理商"
        :visible.sync="franchiseeDialog"
        width="520px"
        center
      >
        <div class="f_r_m_c" style="width: 100%">
          <span>代理商：</span>
          <div class="f1" style="width: 0">
            <el-select
              v-model="editInfo.admin_id"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in franchiseeList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="franchiseeDialog = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button type="primary" @click="submitFranchisee">{{
            $t('action.comfirm')
          }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data () {
    let checkStatus = (rule, value, callback) => {
      if (!this.subForm.status) {
        callback(new Error('请选择审核结果'))
      } else {
        callback()
      }
    }
    return {
      userInfo: {},
      loading: false,
      addText: {
        0: {
          type: 'info',
          text: '用户'
        },
        1: {
          type: '',
          text: '平台'
        }
      },
      statusText: {
        1: {
          type: 'info',
          text: '申请中'
        },
        2: {
          type: '',
          text: '已授权'
        },
        3: {
          type: 'danger',
          text: '取消授权'
        },
        4: {
          type: 'danger',
          text: '已驳回'
        }
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      range: '',
      searchForm: {
        page: 1,
        limit: 10,
        status: 0,
        name: ''
      },
      tableData: [],
      total: 0,
      count: {},
      showApply: false,
      applyForm: {
        title: '',
        status: '',
        sh_text: ''
      },
      subForm: {
        id: 0,
        status: 0,
        sh_text: '',
        type: 1
      },
      subFormRules: {
        status: {
          required: true,
          validator: checkStatus,
          trigger: 'blur'
        }
      },
      franchiseeList: [],
      franchiseeDialog: false,
      admin_id: '', // 代理商id
      editInfo: {
        admin_id: ''
      }
    }
  },
  created () {
    this.userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'))
    this.getBaseInfo()
  },
  activated () {
    this.getTableDataList(1)
  },
  methods: {
    async getBaseInfo () {
      let { code, data } = await this.$api.account.adminSelect()
      if (code !== 200) return
      this.franchiseeList = data
    },
    resetForm (form) {
      this.range = ''
      this.$refs[form].resetFields()
      this.getTableDataList(1)
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async toChange (index) {
      this.searchForm.status = index
      this.getTableDataList(1)
    },
    async getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let { range } = this
      let searchForm = JSON.parse(JSON.stringify(this.searchForm))
      if (range && range.length > 0) {
        searchForm.start_time = parseInt(range[0] / 1000)
        searchForm.end_time = parseInt(range[1] / 1000) + 24 * 3600 - 1
      } else {
        searchForm.start_time = ''
        searchForm.end_time = ''
      }
      if (searchForm.status === -1) {
        searchForm.is_update = 1
        delete searchForm.status
      }
      let { code, data } = await this.$api.technician.coachList(
        searchForm
      )
      this.loading = false
      if (code !== 200) return
      let { all, nopass, ing, pass, total, update_num: update } = data
      this.tableData = data.data
      this.total = total
      this.count = { all, nopass, ing, pass, update }
    },
    async toShowApply (id = 0, type = 1) {
      let methodModel = type === 2 ? 'coachUpdateInfo' : 'coachInfo'
      let { code, data } = await this.$api.technician[methodModel]({ id })
      if (code !== 200) return
      let arr = ['id_card', 'license', 'self_img']
      arr.map(item => {
        data[item] = data[item].length > 0 ? data[item].map(aitem => {
          return { url: aitem }
        }) : []
      })
      this.applyForm = data
      this.subForm = {
        id,
        status: 2,
        sh_text: '',
        type
      }
      this.showApply = !this.showApply
    },
    confirmDel (id, status) {
      this.$confirm(this.$t(status === 3 ? 'tips.confirmNoPass' : 'tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.updateItem(id, status)
      }).catch(() => { })
    },
    async updateItem (id, status) {
      this.$api.technician.coachUpdate({ id, status }).then((res) => {
        if (res.code === 200) {
          this.$message.success(this.$t(status === -1 ? 'tips.successDel' : 'tips.successOper'))
          if (status === -1) {
            this.searchForm.page =
              this.searchForm.page <
                Math.ceil((this.total - 1) / this.searchForm.limit)
                ? this.searchForm.page
                : Math.ceil(
                  (this.total - 1) / this.searchForm.limit
                )
          }
          this.getTableDataList()
        } else {
          if (status === -1) return
          this.getTableDataList()
        }
      })
    },
    submitForm () {
      this.$refs['subForm'].validate((valid) => {
        if (valid) {
          let param = JSON.parse(JSON.stringify(this.subForm))
          let methodModel = param.type === 2 ? 'coachUpdateCheck' : 'coachUpdate'
          delete param.type
          this.$api.technician[methodModel](param).then((res) => {
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successSub'))
              this.showApply = false
              this.getTableDataList()
            }
          })
        }
      })
    },
    confirmedit (row) {
      let item = JSON.parse(JSON.stringify(row))
      if (item.admin_id === 0) {
        item.admin_id = ''
      }
      this.editInfo = item
      this.franchiseeDialog = true
    },
    submitFranchisee () {
      let { id, admin_id: aid = 0 } = this.editInfo
      if (!aid) {
        this.$message.error(`请选择代理商`)
        return
      }
      this.$api.technician.coachUpdate({ id, admin_id: aid }).then((res) => {
        if (res.code === 200) {
          this.$message.success(
            this.$t(
              'tips.successOper'
            )
          )
          this.franchiseeDialog = false
          this.getTableDataList()
        }
      })
    }
  },
  filters: {
    handleTime (val, type) {
      let time =
        type === 1
          ? moment(val * 1000).format('YYYY-MM-DD')
          : type === 2
            ? moment(val * 1000).format('HH:mm:ss')
            : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.f_r_m_c {
  display: flex;
  align-items: center;
}
.f1 {
  display: flex;
  flex: 1;
}
.el-form {
  .el-input {
    width: 200px;
  }
  .el-image {
    width: 120px;
    height: 120px;
  }
  .el-textarea {
    width: 600px;
  }
}
</style>
